// pages/exercise/parse.js
const db = wx.cloud.database()
var app = getApp();
var exercise_id
Page({
  data: {
    index: 0,
    // exercise: null,
    userTest: null,
    openid:'',
    questionList: [],
    showModal: false,
  },
  swiper: function(e){
    var current = e.detail.current
    if(current == this.data.questionList.length){
      current = 0
    }
    this.setData({
      index: current
    })
  },
  
  jump: function(e){
    var current = e.currentTarget.dataset.current
    this.setData({
      index: current,
      showModal: false
    })
  },
  
  onLoad: function(options){
    exercise_id = options._id
    var that = this
    var openid = wx.getStorageSync('openid')
    if(!openid){
      wx.setStorageSync('returnUrl', '/pages/exercise/parse?_id='+exercise_id)
      wx.navigateTo({
        url: '../index/welcome',
      })
      return false
    }
    that.setData({
      openid
    })
  },
  onShow: function () {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    //查询exercise
    db.collection('exercise').doc(exercise_id).get({
      success: res => {
        wx.setNavigationBarTitle({
          title: res.data.title,
        }) 
      }
    })
    //查询userTest表
    db.collection('userTest').where({
      exercise_id,
      _openid: that.data.openid
    }).get({
      success: res => {
        console.log('userTest',res.data[0])
        that.setData({
          userTest: res.data[0]
        })
      }
    })
    //查询questionBank表数据
    db.collection('questionBank').where({
      exercise_id
    }).get({
      success: res => {
        var questionList = res.data
        questionList.forEach(function(item,index){
          db.collection('userTest').where({
            _openid: item._openid
          }).get({
            success: res => {
              console.log(index,that.data.userTest.result[index])
              questionList[index].choosed = that.data.userTest.result[index].choosed
              questionList[index].flag = that.data.userTest.result[index].flag
            }
          })
        })
        setTimeout(function(){
          that.setData({
            questionList
          })
          console.log('questionList',questionList)
          wx.hideLoading()
        },1000)
        
      },
      fail: err => {
        console.error('error', err)
      }
    })
  },
  
  showMask: function(){
    this.setData({
      showModal: true
    })
  },
  // 弹出层里面的弹窗
  hideMask: function () {
    this.setData({
      showModal: false
    })
  },
})
